using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MinimalistFoodStreet.BackEnd.Infrastructure.Attributes;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Request.Tables;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response.Tables;
using MinimalistFoodStreet.BackEnd.Infrastructure.EFCore;
using MinimalistFoodStreet.BackEnd.Server.TableEFCore;
using MinimalistFoodStreet.BackEnd.Server.Server.RequestExtend.Tables;
using MinimalistFoodStreet.BackEnd.Server.Server.ResponseExtend.Tables;
using MinimalistFoodStreet.BackEnd.Server.IServer.Tables;

namespace MinimalistFoodStreet.BackEnd.Server.Server.Tables
{
    [InjectClass]
    public class PromotionsService : IPromotionsService
    {
        private readonly ServerRepository _serverRepository;
        public PromotionsService(DbContext dbContext)
        {
            _serverRepository = new ServerRepository(dbContext);
        }

        public async Task<ResponseApiDto> AddAsync(RequestCreatePromotionsDto dto, int sid)
        {
            int affectedRows = 0;
            await _serverRepository.ExecuteInTransactionAsync(async () =>
            {
                Promotion promotion = dto.ToCreateEntity();
                // 检查该商品有没有活动
                if (await _serverRepository.promotionsEFCore.Query(d => d.PGoodId == dto.goodId&&d.PEndTime>DateTime.Now).AnyAsync())
                {
                    // 立即结束活动
                    List<Promotion> processingPromotions=await _serverRepository.promotionsEFCore.Query(d => d.PGoodId == dto.goodId && d.PEndTime > DateTime.Now).ToListAsync();
                    for (int i = 0; i < processingPromotions.Count; i++)
                    {
                        Promotion processingPromotion = processingPromotions[i];
                        processingPromotion.PEndTime = DateTime.Now.AddMinutes(-1);
                    }
                    affectedRows += await _serverRepository.promotionsEFCore.UpdateAsync(processingPromotions);
                }
                promotion.PSupplierId = sid;
                affectedRows += await _serverRepository.promotionsEFCore.AddAsync(promotion);
            }, () =>
            {
                affectedRows = 0;
                return null;
            });
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> UpdateAsync(RequestUpdatePromotionsDto dto)
        {
            Promotion promotions = await _serverRepository.promotionsEFCore.Query(d => d.PId == dto.id).SingleOrDefaultAsync();
            if (promotions == null)
            {
                return ResponseApiDto.Fail("该实例不存在");
            }

            promotions.PId = dto.id;
            promotions.PDiscountPrice = dto.discountPrice;
            promotions.PStartTime = dto.startTime;
            promotions.PEndTime = dto.endTime;
            int affectedRows = await _serverRepository.promotionsEFCore.UpdateAsync(promotions);
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> DeleteAsync(RequestIdPromotionsDto dto)
        {
            int affectedRows = await _serverRepository.promotionsEFCore.Query(d => d.PId == dto.id).ExecuteDeleteAsync();
            if (affectedRows == 0)
            {
                return ResponseApiDto.Fail("该实例不存在");
            }
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> DetailAsync(RequestIdPromotionsDto dto)
        {
            Promotion promotions = await _serverRepository.promotionsEFCore.Query(d => d.PId == dto.id).SingleOrDefaultAsync();
            if (promotions == null)
            {
                return ResponseApiDto.Fail("该实例不存在");
            }
            return ResponseApiDto.Ok("数据已获取", promotions.ToResponseDto());
        }

        public async Task<ResponseApiDto> PaginationAsync(int page, int limit, string? key)
        {
            int total = 0;
            List<Promotion> promotionss = await _serverRepository.promotionsEFCore.Pagination(d => key == null, false, d => d.PId, out total, page, limit).ToListAsync();
            List<ResponsePromotionsDto> responsePromotionsDtos = promotionss.Select(d => d.ToResponseDto()).ToList();
            return ResponseApiDto.Ok("数据已获取", new { data = responsePromotionsDtos, total = total });
        }
    }
}